package com.atjinggu.jinggumail.oauth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atjinggu.jinggumail.common.constant.AuthConstant;
import com.atjinggu.jinggumail.common.utils.HttpUtils;
import com.atjinggu.jinggumail.common.utils.R;
import com.atjinggu.jinggumail.oauth.feign.MemberFeignService;
import com.atjinggu.jinggumail.common.vo.MemberResponseVo;
import com.atjinggu.jinggumail.oauth.vo.SocialUser;
import com.google.common.collect.Maps;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author jingming
 * @Type OAuth2Controller.java
 * @Desc
 * @date 2021/3/2 16:03
 */
@Controller("/oauth2.0")
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;


    @GetMapping("/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        HashMap<String,String> param = Maps.newHashMap();
        param.put("client_id","2636917288");
        param.put("client_secret","6a263e9284c6c1a74a62eadacc11b6e2");
        param.put("grant_type","authorization_code");
        param.put("redirect_code","http://jinggumail.com/oauth2.0/weibo/success");
        param.put("code",code);
        HttpResponse post = HttpUtils.doPost("api.weibo.com", "oauth2/access_token", "post", null, param, "");

        if(post.getStatusLine().getStatusCode() != 200){
            return "redirect:http://oauth.jinggumail.com/login.html";
        }

        //成功，则判断是否第一次登陆
        String s = EntityUtils.toString(post.getEntity());
        SocialUser socialUser = JSON.parseObject(s, SocialUser.class);
        //登陆或者注册这个社交用户
        R r = memberFeignService.oauthLogin(socialUser);
        if(r.getCode() != 0){
            return "redirect:http://oauth.jinggumail.com/login.html";
        }
        MemberResponseVo data = r.getData("data", new TypeReference<MemberResponseVo>() {
        });
        session.setAttribute(AuthConstant.LOGIN_USER,data);
        return "redirect:http://jinggumail.com";


    }
}